package com.tao.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tao.ucenter.mapper.UserMapper;
import com.tao.ucenter.model.dto.AuthParamsDto;
import com.tao.ucenter.model.dto.UserExt;
import com.tao.ucenter.model.po.Menu;
import com.tao.ucenter.model.po.User;
import com.tao.ucenter.service.AuthService;
import com.tao.ucenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author taohongrun
 * @since 2024/11/21
 */
@Service
@Slf4j
@Validated
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserDetailsService, UserService {

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //判断是否为合法用户，走的该逻辑
        //由于不是接口层，无法自动转换json，必须手动转换
        AuthParamsDto authParamsDto = null;

        try {
            authParamsDto = JSON.parseObject(s,AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}",s);
            throw new RuntimeException("认证请求数据格式不对");
        }

        String authType = authParamsDto.getAuthType();
        AuthService authService =  applicationContext.getBean(authType + "_authservice",AuthService.class);
        UserExt user = authService.execute(authParamsDto);

        return getUserPrincipal(user);

    }

    /**
     * @description 查询用户信息
     * @param user  用户id，主键
     * @return com.tao.ucenter.model.po.User 用户信息
     * @author Mr.M
     * @date 2022/9/29 12:19
     */
    public UserDetails getUserPrincipal(UserExt user){
        // 创建一个权限集合
        String[] authorities = getAuthorities(user.getId());


        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection

        String password = user.getPassword();
        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转json
        String userString = JSON.toJSONString(user);
        //创建UserDetails对象
        UserDetails userDetails = org.springframework.security.core.userdetails.User.withUsername(userString).password(password ).authorities(authorities).build();
        return userDetails;
    }

    public String[] getAuthorities(String userId){
         return userMapper.selectPermissionByUserId(userId).toArray(String[]::new);
    }

}
